
import { MockMethod } from 'vite-plugin-mock'
import pkg from 'mockjs';
const { Random, mock } = pkg; // 或者 const { Random } = pkg;

const formList: any[] = []
const formTypes = ['1', '2', '3']

for (let i = 1; i <= 50; i++) {
  formList.push({
    id: i,
    formName: Random.ctitle() + '表单',
    formDesc: Random.csentence(5, 10),
    formType: Random.pick(formTypes),
    formConfig: JSON.stringify({
      fields: [
        {
          id: 'field_' + i,
          type: 'input',
          label: '字段' + i,
          value: '',
          props: {
            placeholder: '请输入'
          }
        }
      ]
    }),
    createTime: Random.datetime('yyyy-MM-dd HH:mm:ss')
  })
}

export default [

  {
    url: '/api/form/list',
    method: 'get',
    response: ({ query }: any) => {
      const { pageNum = 1, pageSize = 10, formName, formType } = query
      const filteredList = formList.filter((item) => {
        if (formName && !item.formName.includes(formName)) return false
        if (formType && item.formType !== formType) return false
        return true
      })
      const pagedList = filteredList.slice(
        (pageNum - 1) * pageSize,
        pageNum * pageSize
      )
      return {
        code: 200,
        message: 'success',
        data: {
          rows: pagedList,
          total: filteredList.length
        }
      }
    }
  },
  {
    url: '/forms/:id',
    method: 'get',
    response: ({ url }: any) => {
      const id = url.split('/').pop()
      const form = formList.find((item) => item.id === parseInt(id))
      return {
        code: 200,
        message: 'success',
        data: form
      }
    }
  },
  {
    url: '/forms',
    method: 'post',
    response: ({ body }: any) => {
      const newForm = {
        id: formList.length + 1,
        ...body,
        createTime: new Date().toISOString()
      }
      formList.unshift(newForm)
      return {
        code: 200,
        message: 'success'
      }
    }
  },
  {
    url: '/forms',
    method: 'put',
    response: ({ body }: any) => {
      const index = formList.findIndex((item) => item.id === body.id)
      if (index !== -1) {
        formList[index] = { ...formList[index], ...body }
      }
      return {
        code: 200,
        message: 'success'
      }
    }
  },
  {
    url: '/forms/:id',
    method: 'delete',
    response: ({ url }: any) => {
      const id = url.split('/').pop()
      const index = formList.findIndex((item) => item.id === parseInt(id))
      if (index !== -1) {
        formList.splice(index, 1)
      }
      return {
        code: 200,
        message: 'success'
      }
    }
  }
] as MockMethod[]
